package com.songlanyun.interceptor;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.annotation.AuthIgnore;
import com.songlanyun.common.config.resttplconfig.RegisterComponent;
import com.songlanyun.common.utils.R;
import com.songlanyun.common.utils.RedisKeys;
import com.songlanyun.modules.applyareaagent.entity.ApplyAreaAgentEntity;
import com.songlanyun.modules.applyareaagent.service.ApplyAreaAgentService;
import com.songlanyun.modules.shop.entity.ShopAdminRelationEntity;
import com.songlanyun.modules.shop.entity.ShopEntity;
import com.songlanyun.modules.shop.service.ShopAdminRelationService;
import com.songlanyun.modules.shop.service.ShopService;
import com.songlanyun.modules.user.dao.SysUserDao;
import com.songlanyun.modules.user.entity.SysUserEntity;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器  -- 拦截后台接口
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    @Autowired
    private ShopAdminRelationService shopAdminRelationService;

    @Autowired
    private ApplyAreaAgentService applyAreaAgentService;

    @Resource
    private SysUserDao sysUserDao;

    @Resource
    private ShopService shopService;

    @Autowired
    private RegisterComponent registerComponent;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        registerComponent.validateCode();
        AuthIgnore annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthIgnore.class);
        } else {
            return true;
        }

        //如果有@IgnoreAuth注解，则不验证token
        if (annotation != null) {
            return true;
        }

        String token = request.getHeader("token");//header方式
        String uid = redisTemplate.opsForValue().get(RedisKeys.getTokenConfigKey(token));

        if (!StringUtils.hasText(token)
                || !StringUtils.hasText(uid)) {
            response.setCharacterEncoding("UTF-8"); //设置编码格式
            response.setContentType("application/json");
            R responseBean = R.error(-400, "访问需要令牌");
            response.getWriter().write(JSON.toJSONString(responseBean));
            return false;
        }

        //登录成功后，判断
        //查询用户信息
        SysUserEntity user = sysUserDao.selectById(uid);

        if (user.getIsShop()) {
            // 先按非联盟商家模式查询店铺信息
            ShopEntity shop = shopService.getShopByAdminId(user.getUserId(), false);

            // 如果按非联盟商家模式查询不到店铺信息，则再尝试按联盟商家查询店铺信息
            if(shop == null) {
                shop = shopService.getShopByAdminId(user.getUserId(), true);
            }

            if (shop != null) {
                request.setAttribute("shop_id", shop.getId());
            }
        }

        if (user.getIsAreaAgent()) {
            ApplyAreaAgentEntity applyAreaAgentEntity = applyAreaAgentService.getOne(
                    new LambdaQueryWrapper<ApplyAreaAgentEntity>()
                            .eq(ApplyAreaAgentEntity::getAdminId, user.getUserId())
            );
            if (applyAreaAgentEntity != null) {
                request.setAttribute("area_agent_id", applyAreaAgentEntity.getId());
            }
        }

        request.setAttribute("uid", uid);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }
}
